﻿using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace updater
{
	internal sealed class Program
	{
		private static Exception generalEx = new Exception();
		internal static string newversion = null;
		
		private static void Main(string[] args)
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			
			MessageBoxButtons buttons = MessageBoxButtons.YesNo;
			MessageBoxIcon IconType = MessageBoxIcon.Question;
			string AskCaption = null;
			string OrigFilePath = System.IO.Path.Combine(Application.StartupPath, "hkgoldenhighlight.scr");
			
			
			if(System.IO.Path.GetFileName(Application.ExecutablePath).Equals("hkgoldenhighlight-updater.exe") == false)
			{
				AskCaption = "請將此程式的檔案名稱改為：\r\nhkgoldenhighlight-updater.exe\r\n此程式即將結束。";
				buttons = MessageBoxButtons.OK;
				IconType = MessageBoxIcon.Hand;
			}
			else if(System.IO.File.Exists(OrigFilePath) == false)
			{
				AskCaption = "請將此程式檔放置於要更新的 hkgoldenhighlight.scr 同一目錄下。\r\n此程式即將結束。";
				buttons = MessageBoxButtons.OK;
				IconType = MessageBoxIcon.Hand;
			}
			else
			{
				newversion = CheckIfItsANewestVersion();
				
				if(args.Length > 0)
				{
					if(args[0] == "/update")
					{
						Application.Run(new MainForm());
					}
					else
					{
						Application.Exit();
					}
				}
				else
				{
					if(newversion == null)
					{
						AskCaption = "在查詢最新版本號時出現錯誤：\r\n\r\n" + generalEx.Message + "\r\n\r\n如果你想重試，請重新開啟此程式。\r\n此程式即將結束。";
						buttons = MessageBoxButtons.OK;
						IconType = MessageBoxIcon.Hand;
					}
					else
					{
						string OrigFileVersion = FileVersionInfo.GetVersionInfo(OrigFilePath).FileVersion;
						AskCaption = "已經找到此程式所屬的目錄有 hkgoldenhighlight.scr 程式檔，\r\n\r\n本機現存版本：" + OrigFileVersion + "\r\n網上最新版本：" + newversion + "\r\n\r\n您是否要更新（或更舊）此程式？";
					}
				}
			}
			
			DialogResult result = MessageBox.Show(AskCaption, "手動更新", buttons, IconType, MessageBoxDefaultButton.Button1);
					
			if(result == DialogResult.OK || result == DialogResult.No)
			{
				Application.Exit();
			}
			else
			{
				Application.Run(new MainForm());
			}
		}
		#region mini-stuffs
		private static string CheckIfItsANewestVersion()
	    {
			string result = null;
			
	        try
	        {
	            // download information
				byte[] Data = new byte[4096]; int Length = 0;
				using (System.Net.WebClient Client = new System.Net.WebClient()) {
					using (System.IO.Stream Stream = Client.OpenRead("http://hkgoldenhighlight.googlecode.com/svn/trunk/hkgoldenhighlight/version.txt")) {
						while (true) {
							if (Length + 256 >= Data.Length) Array.Resize<byte>(ref Data, Data.Length << 1);
							int n = Stream.Read(Data, Length, 256);
							if (n != 0) {
								Length += n;
							} else break;
						}
						Stream.Close();
					}
				}
				Array.Resize<byte>(ref Data, Length);
				// parse information
				System.Text.Encoding Encoding = new System.Text.UTF8Encoding();
				string Text = new string(Encoding.GetChars(Data));
				if (Text.Length != 0 && Text[0] == '\uFEFF') Text = Text.Substring(1);
				string[] Lines = Text.Split(new char[] { '\r', '\n' });
				if (Lines.Length == 0 || !Lines[0].Equals("$hkgoldenhighlight", StringComparison.OrdinalIgnoreCase))
	            {
					throw new Exception("在檢查期間發生錯誤：更新資訊檔損壞。");
	            }
	            else
	            {
	                for (int i = 1; i < Lines.Length; i++)
	                {
	                    int h = Lines[i].IndexOf('=');
	                    if (h >= 0)
	                    {
	                        string a = Lines[i].Substring(0, h).TrimEnd(new char[0]);
	                        string b = Lines[i].Substring(h + 1).TrimStart(new char[0]);
	                        if (a.Equals("version", StringComparison.OrdinalIgnoreCase))
	                        {
	                            result = b;
	                        }
	                    }
	                }
	            }
	        }
	        catch (Exception ex)
	        {
	            generalEx = ex;
	        }
	        
	        return result;
	    }
		#endregion
	}
}
